<template>
  <el-form ref="formData" :model="formData" :rules="rules" label-width="130px" v-loading="loading">
    <vision-form ref="form" :formData="formData" @resetForm="resetForm" @submitForm="submitForm"></vision-form>
    <template v-if="formData.visionDemandType != 4">
      <div class="form-item-box">
        <div class="description">
          <el-form-item
            v-for="(item, index) in formData.productIntroduction"
            label
            :key="index"
            :prop="'productIntroduction.' + index + '.value'"
            :rules="{required: true, message:  item.key + '内容不能为空', trigger: 'blur'}"
            label-width="0"
          >
            <div class="form-item-label">
              <el-form-item
                label
                :key="index"
                :prop="'productIntroduction.' + index + '.key'"
                :rules="{required: true, message:  '标题不能为空', trigger: 'blur'}"
                label-width="0"
              >
                <span @click.prevent="item.edit = true">
                  <template v-if="!item.edit">
                    {{index+1}}
                    {{item.key}}
                    <i class="el-icon-edit"></i>
                  </template>
                  <el-input
                    v-model="item.key"
                    size="mini"
                    ref="mark "
                    autofocus
                    v-focus
                    @blur.prevent="editIntroduct(item)"
                    v-if="item.edit"
                  ></el-input>
                </span>
                <el-button
                  type="danger"
                  @click.prevent="removeIntroduct(item)"
                  icon="el-icon-delete"
                  circle
                  v-if="index !== 0 && !item.edit"
                  size="mini"
                ></el-button>
              </el-form-item>
            </div>
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5}"
              placeholder="请输入内容"
              v-model="item.value"
              size="mini"
            ></el-input>
          </el-form-item>
          <el-button
            @click.prevent="addIntroductList"
            type="primary"
            size="mini"
            icon="el-icon-circle-plus-outline"
          >新增模板</el-button>
        </div>
        <div class="referenceList">
          <el-form-item
            v-for="(item, index) in formData.referenceList"
            label
            :key="index"
            :prop="'referenceList.' + index + '.note'"
            :rules="{required: true, message:  '内容不能为空', trigger: 'blur'}"
            label-width="0"
          >
            <div class="form-item-label">
              <el-form-item
                v-for="(itemURL,URLindex) in item.referenceUrl"
                label
                :key="URLindex"
                label-width="0"
                :prop="'referenceList.' + index + '.referenceUrl.' + URLindex + '.url'"
                :rules="{required: true, message:  'URL不能为空', trigger: 'blur'}"
              >
                <el-link type="primary" :href="itemURL.url" target="_blank">
                  <i class="el-icon-paperclip" v-if="!itemURL.edit"></i>
                </el-link>
                <span @click.prevent="itemURL.edit = true">
                  <template v-if="!itemURL.edit">
                    {{itemURL.url}}
                    <i class="el-icon-edit"></i>
                  </template>
                  <el-input
                    v-model="item.referenceUrl[URLindex].url"
                    size="mini"
                    ref="mark "
                    autofocus
                    v-focus
                    @blur.prevent="editReferenceURL(itemURL)"
                    v-if="itemURL.edit"
                  ></el-input>
                </span>
                <i
                  class="el-icon-circle-plus-outline"
                  @click.prevent="addURL(index)"
                  v-if="URLindex === 0 && !itemURL.edit"
                ></i>
                <i
                  class="el-icon-delete"
                  @click.prevent="removeURL(index,URLindex)"
                  v-if="URLindex !== 0 && !itemURL.edit"
                ></i>
              </el-form-item>
              <el-button
                type="danger"
                @click.prevent="removeReferenceURL(item)"
                icon="el-icon-delete"
                circle
                v-if="index !== 0 && !item.edit"
                size="mini"
              ></el-button>
            </div>
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5}"
              placeholder="请输入内容"
              v-model="item.note"
              size="mini"
            ></el-input>
          </el-form-item>
          <el-button
            @click.prevent="addReferenceURL"
            type="primary"
            size="mini"
            icon="el-icon-circle-plus-outline"
          >新增模板</el-button>
        </div>
        <el-timeline v-if="formData.visionDemandId">
          <el-timeline-item
            :timestamp="formData.createTime | createTime"
          >需求提出者： {{formData.createUserName}}</el-timeline-item>
          <el-timeline-item
            :timestamp=" formData.updateTime | updateTime "
          >最后修改人： {{formData.updateUserName}} 修改次数：{{formData.updateNumber}}</el-timeline-item>
        </el-timeline>
      </div>
    </template>
    <div v-else class="videoInfo">
      <div class="InfoTitle">
        视频详细内容
        <p>(具体制作要求\字幕\音乐风格\参考链接\拍摄素材、三维模型等)</p>
      </div>
      <editor-bar v-model="formData.visionDemandVideoInfoDTO.videoInfo"></editor-bar>
    </div>
  </el-form>
</template>
<script>
const ERR_OK = 200;
import { formatDate } from "assets/js/date";
import visionForm from "./vision-form";
import quillEditor from "components/quill-editor/quill-editor";
import EditorBar from "components/quill-editor/wang-editor";
export default {
  data() {
    return {
      loading: false,
      formData: {
        createUserId: this.$store.getters.userId,
        visionDemandType: "",
        visionDemandName: "",
        productId: "",
        visionDemandDominantType: 2,
        predictResultImgTotal: "",
        visionDemandVideoInfoDTO: {
          videoSize: "",
          videoFormat: "",
          videoProportion: "",
          videoResolution: "",
          videoTime: 0,
          videoUsage: "",
          videoInfo: " "
        },
        productIntroduction: [
          {
            edit: false,
            value: "",
            key: "产品介绍"
          }
        ],
        referenceList: [
          {
            note: "",
            referenceUrl: [{ url: "参考链接", edit: false }]
          }
        ],
        businessUnitId: "",
        productCategoryId: "",
        pageViewsPercentage: 0,
        unitSessionPercentage: 0.0
      },
      rules: {
        visionDemandName: [
          {
            required: "change",
            message: "请输入需求名称",
            trigger: "blur"
          }
        ],
        visionDemandType: [
          {
            required: "change",
            message: "请选择类型",
            trigger: "change"
          }
        ],
        productId: [
          {
            required: true,
            message: this.$t("m.placeholder.selectProductModelNumber"),
            trigger: "change"
          }
        ],
        pageViewsPercentage: [
          {
            required: "change",
            message: "请输入",
            trigger: "blur"
          }
        ],
        unitSessionPercentage: [
          {
            required: "change",
            message: "请输入",
            trigger: "blur"
          }
        ],
        "visionDemandVideoInfoDTO.videoSize": [
          {
            required: true,
            message: "请输入视频大小M",
            trigger: "blur"
          }
        ],
        "visionDemandVideoInfoDTO.videoFormat": [
          {
            required: true,
            message: "请输入视频格式",
            trigger: ["blur", "change"]
          }
        ],
        "visionDemandVideoInfoDTO.videoProportion": [
          {
            required: true,
            message: "请输入视频比例",
            trigger: ["blur", "change"]
          }
        ],
        "visionDemandVideoInfoDTO.videoResolution": [
          {
            required: true,
            message: "请输入视频分辨率",
            trigger: ["blur", "change"]
          }
        ],
        "visionDemandVideoInfoDTO.videoTime": [
          {
            required: true,
            message: "请输入视频时长s",
            trigger: "blur"
          }
        ],
        "visionDemandVideoInfoDTO.videoUsage": [
          {
            required: true,
            message: "请输入视频用途",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    if (this.$route.query.visionDemandId) {
      this.getVisionDemandById(this.$route.query.visionDemandId);
      this.loading = true;
    } else {
      this.loading = false;
    }
  },
  filters: {
    createTime(data) {
      var date = new Date(data);
      return "需求提出日期：" + formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    updateTime(data) {
      var date = new Date(data);
      return "需求修改日期：" + formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  directives: {
    focus: {
      // 指令的定义
      inserted: function(el) {
        // 聚焦元素
        el.querySelector("input").focus();
      }
    }
  },
  methods: {
    //编辑产品详情标题
    editIntroduct(item) {
      if (item.key) {
        item.edit = false;
      } else {
        this.$message.error("标题不能为空");
      }
    },
    //编辑url标题
    editReferenceURL(item) {
      if (item.url) {
        item.edit = false;
      } else {
        this.$message.error("URL不能为空");
      }
    },
    //删除文本框
    removeIntroduct(item) {
      var index = this.formData.productIntroduction.indexOf(item);
      if (index !== -1) {
        this.formData.productIntroduction.splice(index, 1);
      }
    },
    //删除文本框
    removeReferenceURL(item) {
      var index = this.formData.referenceList.indexOf(item);
      if (index !== -1) {
        this.formData.referenceList.splice(index, 1);
      }
    },
    removeURL(index, URLindex) {
      this.formData.referenceList[index].referenceUrl.splice(URLindex, 1);
    },
    // 新增文本框
    addIntroductList() {
      this.formData.productIntroduction.push({
        value: "",
        key: "产品介绍",
        edit: false
      });
    },
    // 新增URL文本框
    addReferenceURL() {
      this.formData.referenceList.push({
        referenceUrl: [{ url: "https://www.amazon.it", edit: false }],
        note: "",
        visionDemandId: this.formData.visionDemandId
          ? this.formData.visionDemandId
          : "" //编辑需要添加
      });
    },
    addURL(index) {
      this.formData.referenceList[index].referenceUrl.push({
        url: "https://www.amazon.it",
        edit: false
      });
    },

    //URL转stringify
    referenceURLstringify(referenceLis) {
      referenceLis.forEach(
        item => (item.referenceUrl = JSON.stringify(item.referenceUrl))
      );
      return referenceLis;
    },
    //通过id 获取 视觉需求对象
    getVisionDemandById(visionDemandId) {
      this.$ajax({
        method: "get",
        url:
          this.GLOBAL.oaVisionDemand +
          "/visionDemand/getVisionDemandById?visionDemandId=" +
          visionDemandId
      }).then(res => {
        this.loading = false;
        if (res.data.code === ERR_OK) {
          let form = res.data.data.visionDemand;
          form.productIntroduction = JSON.parse(form.productIntroduction);
          form.productId = form.productId;
          form.referenceList = res.data.data.referenceList;
          form.referenceList.forEach(item => {
            item.referenceUrl = JSON.parse(item.referenceUrl);
          });
          //form.pageViewsPercentage = Number((form.pageViewsPercentage*100).toFixed(4))
          form.unitSessionPercentage = Number(
            (form.unitSessionPercentage * 100).toFixed(4)
          );
          form.visionDemandVideoInfoDTO = form.visionDemandVideoInfoVO;
          this.formData = form;
          if (this.formData.visionDemandStatusId === 9) {
            //是否状态完成
            this.$router.push({ path: "/OACenter/visualDesign/demandList" });
          }
        } else {
          this.$router.push({ path: "/OACenter/visualDesign/demandList" });
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let formData = JSON.parse(JSON.stringify(this.formData));
          formData.referenceList = this.referenceURLstringify(
            formData.referenceList
          );
          formData.productIntroduction = JSON.stringify(
            formData.productIntroduction
          );
          //  formData.pageViewsPercentage = Number(formData.pageViewsPercentage/100).toFixed(4)
          formData.unitSessionPercentage = Number(
            formData.unitSessionPercentage / 100
          ).toFixed(4);
          if (this.formData.visionDemandId) {
            //编辑新增
            formData.updateUserId = this.$store.getters.userId;
          }
          this.$refs.form.loading = true;
          this.$ajax({
            method: "post",
            url:
              this.GLOBAL.oaVisionDemand +
              "/visionDemand/saveDesignDominantDemand",
            data: formData
          }).then(res => {
            this.$refs.form.loading = false;
            if (res.data.code === ERR_OK) {
              if (this.formData.visionDemandId) {
                this.$message.success("修改成功");
              } else {
                this.$message.success("新增成功");
              }
              this.promptReturn(res.data.data);
            } else {
              this.$message.error(res.data.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
    promptReturn(id) {
      this.$confirm("是否返回页面", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$router.push({ path: "/OACenter/visualDesign/demandList" });
        })
        .catch(() => {
          this.getVisionDemandById(id);
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  components: {
    visionForm,
    quillEditor,
    EditorBar
  }
};
</script>
<style lang="stylus" scoped>
.form-item-box {
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
  vertical-align: top;

  .el-button--primary {
    margin-top: 10px;
  }

  .el-timeline {
    margin-top: 20px;
  }

  .description, .referenceList {
    display: inline-block;
    vertical-align: top;
    margin-top: 20px;
    width: 400px;
    margin-right: 20px;
    padding-right: 20px;
    border-right: 1px solid #cccccc;

    .el-form-item {
      display: block;
      margin-bottom: 10px;
    }

    .form-item-label {
      color: #333333;

      span {
        float: left;
        display: block;
        max-width: 200px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }

      .el-link {
        float: left;
        margin-right: 5px;
      }

      .el-form-item {
        margin-bottom: 0;
      }

      .el-icon-edit {
        color: #409eff;
      }

      .el-button--danger {
        float: right;
        margin-top: 5px;
      }
    }
  }

  .referenceList {
    .form-item-label {
      position: relative;

      .el-button--danger {
        position: absolute;
        right: 0;
        top: 0;
      }
    }
  }
}

.videoInfo {
  margin-top: 15px;

  .InfoTitle {
    font-size: 16px;
    color: #333333;
    padding: 7px 0;
    font-weight: bold;

    p {
      font-size: 14px;
      color: #f00;
    }
  }
}
</style>